package com.tuotu.gps.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import com.tuotu.gps.entity.LocationInfo;
import com.tuotu.gps.entity.MessageEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by XUYEWEN on 2017/7/23.
 */

public class CollectionFile implements   Runnable{
    private List<LocationInfo> list=new ArrayList<>();
    private String path;
    private Thread mThread;
    private Context mContext;

    public CollectionFile(Context context,String path) {
        this.mContext=context;
        this.path = path;
        mThread=new Thread(this);
        mThread.start();
    }

    public List<LocationInfo> getList() {
        return list;
    }

    @Override
    public void run() {
        if(null!=path)
            queryFile(path);

        Log.i("xyw", "CollectionFile list size="+list.size());
        sortList();
        EventBus.getDefault().post(new MessageEvent(MessageEvent.MSG_FILE_COLLECTIION_DONE));
    }

    public List<LocationInfo> queryFile(String path){
        File file = new File(path);
        if (file.length()>0){
            File[] files = file.listFiles();
            if(null==files){
                return list;
            }
            for (File file1:files) {
                if (file1.isDirectory()){
                    queryFile(file1.getPath());
                }else{

                    String tmpName = file1.getPath();//获取全名,如fire.mp3
                    int index = tmpName.lastIndexOf(".");//"."最后出现的位置
                    String ext = tmpName.substring(index+1).toLowerCase();//文件类型名s获取
                    String name=file1.getPath().substring(0,index);
//                    Log.i("xyw","collection name===="+name);
                    if (file1.length() <= 0) {
                        Utils.deleteFile(name);
                        continue;
                    }
                    if(ext.contains("mp3")){
                        LocationInfo li=new LocationInfo();
                        li.setMp3PathName(file1.getPath());
                        li.setMp3Name(file1.getName());
                        li.setTxtPathName(name+".txt");
                        list.add(li);
                    }
                }
            }
        }
        return list;
    }

    private void sortList(){
        Collections.sort(list, new Comparator<LocationInfo>() {
            @Override
            public int compare(LocationInfo locationInfo, LocationInfo t1) {
                return locationInfo.getMp3PathName().compareTo(t1.getMp3PathName());
            }
        });
    }
}
